package com.xiaoyun.lzg.strategy;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SuffixManager implements BeanPostProcessor {

    private static final Map<String, SuffixStrategy> suffixTypeIndex = new HashMap<>();


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        if (!(bean instanceof SuffixStrategy)) {
            return bean;
        }
        SuffixStrategy decoder = (SuffixStrategy) bean;
        String type = decoder.getType();
        if (suffixTypeIndex.containsKey(type)) {
            throw new IllegalStateException("重复注册");
        }
        suffixTypeIndex.put(type, decoder);
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!(bean instanceof SuffixStrategy)) {
            return bean;
        }
        log.info("BeanPostProcessor after init :{}", bean.getClass());
        return null;
    }


    public String manager(String suffix, String name, InputStream inputStream) {
        SuffixStrategy strategy = suffixTypeIndex.get(suffix);
        if (strategy != null) {
            strategy.marker(name, inputStream);
        }
        return null;
    }
}
